package com.springboot.project.springmail.service;

import com.springboot.project.springmail.bean.Attach;
import com.springboot.project.springmail.bean.Mail;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Copyright: Shanghai Definesys Company.All rights reserved.
 * @Description:
 * @author: chuhaitao
 * @since: 2019/2/12 16:55
 * @history: 1.2019/2/12 created by chuhaitao
 */
@Service
public class MailService {


    private static final String From = "***.com";
    @Autowired
    private JavaMailSender sender;

    public void send(Mail mail) {
        //获取
        Map<String, FileSystemResource> map = null;
        //封装的附件信息<文件名，文件>
        List<Attach> attaches = mail.getAttaches();
        if (attaches != null && !attaches.isEmpty()) {
            map = new HashMap<String, FileSystemResource>();
            for (Attach attach : attaches) {
                String path = attach.getPath() + "/" + attach.getStoredAttachName();
                FileSystemResource fileSystemResource = new FileSystemResource(path);
                map.put(attach.getAttachName(), fileSystemResource);
            }
        }
        //1建立邮件信息
        MimeMessage mailMessage = sender.createMimeMessage();

        //用来封装附件及其他信息
        MimeMessageHelper helper = null;
        try {
            //创建helper对象
            helper = new MimeMessageHelper(mailMessage, true);
            //邮件发送人
            helper.setFrom(From);
            //邮件接收人列表
            helper.setTo(mail.getRecipients());
            //邮件主题
            helper.setSubject(mail.getSubject() == null ? "" : mail.getSubject());
            //发送文本内容
            helper.setText(mail.getContent() == null ? "" : mail.getContent());
            //抄送人
            if (mail.getCcPersons() != null && mail.getCcPersons().length > 0) {
                helper.setCc(mail.getCcPersons());
            }
            //附件信息
            if (map != null) {
                for (Map.Entry<String, FileSystemResource> entry : map.entrySet()) {
                    helper.addAttachment(entry.getKey(), entry.getValue());
                }
            }
            sender.send(mailMessage);

        } catch (Exception e) {

            throw new RuntimeException("发送邮件失败！错误信息：" + e.getMessage());


        }
    }
}
